.TH std::span::first 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::span::first \- std::span::first

.SH Synopsis
   template< std::size_t Count >                                          \fI(since C++20)\fP
   constexpr std::span<element_type, Count> first() const;
   constexpr std::span<element_type, std::dynamic_extent> first(          \fI(since C++20)\fP
   size_type Count ) const;

   Obtains a span that is a view over the first Count elements of this span. The
   program is ill-formed if Count > Extent. The behavior is undefined if Count >
   size().

.SH Return value

   A span r that is a view over the first Count elements of *this, such that r.data()
   == this->data() && r.size() == Count.

.SH Example


// Run this code

 #include <iostream>
 #include <ranges>
 #include <span>
 #include <string_view>

 void print(std::string_view const title,
            std::ranges::forward_range auto const& container)
 {
     auto size{std::size(container)};
     std::cout << title << '[' << size << "]{";
     for (auto const& elem : container)
         std::cout << elem << (--size ? ", " : "");
     std::cout << "};\\n";
 }

 void run_game(std::span<const int> span)
 {
     print("span: ", span);

     std::span<const int, 5> span_first = span.first<5>();
     print("span.first<5>(): ", span_first);

     std::span<const int, std::dynamic_extent> span_first_dynamic = span.first(4);
     print("span.first(4): ", span_first_dynamic);
 }

 int main()
 {
     int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
     print("int a", a);
     run_game(a);
 }

.SH Output:

 int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
 span: [8]{1, 2, 3, 4, 5, 6, 7, 8};
 span.first<5>(): [5]{1, 2, 3, 4, 5};
 span.first\fB(4)\fP: [4]{1, 2, 3, 4};

.SH See also

   last    obtains a subspan consisting of the last N elements of the sequence
           \fI(public member function)\fP
   subspan obtains a subspan
           \fI(public member function)\fP
